from __future__ import absolute_import, division, print_function, unicode_literals

# 用matplotlib可以画图
import matplotlib.pyplot as plt
import numpy as np
# from tensorflow.examples.tutorials.mnist import input_data
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# old_v = tf.logging.get_verbosity()
# tf.logging.set_verbosity(tf.logging.ERROR)

print(tf.__version__)# tensorflow版本

# 显示函数


def plot_image(i, predictions_array, true_label, img):
    predictions_array, true_label, img = predictions_array, true_label[i], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(img, cmap=plt.cm.binary)

    predicted_label = np.argmax(predictions_array)
    if predicted_label == true_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                         100*np.max(predictions_array),
                                         class_names[true_label]),
               color=color)

# 设置x坐标


def plot_value_array(i, predictions_array, true_label):
    predictions_array, true_label = predictions_array, true_label[i]
    plt.grid(False)
    plt.xticks(range(10))
    plt.yticks([])
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)

    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('blue')


# 直接下载mnist如果没有的话
mnist = keras.datasets.mnist

(train_data, train_labels), (eval_data, eval_labels) = mnist.load_data()

# load_data函数有问题

# tf.logging.set_verbosity(old_v)
class_names = ['zero', 'one', 'two', 'three', 'four', 'five',
               'six', 'seven', 'eight', 'night']
# train_data.shape
train_data = train_data / 255.0

eval_data = eval_data / 255.0

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    # reformates data
    keras.layers.Dense(128, activation='relu'),
    # 128个神经元
    keras.layers.Dense(10, activation='softmax')
    # 10个神经元
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
#   更新方式
# 准确率
model.fit(train_data, train_labels, epochs=10)

# 训练
test_loss, test_acc = model.evaluate(eval_data,  eval_labels, verbose=2)
# 测试
print('\nTest accuracy:', test_acc)
model.save('mnistnum.h5')
predictions = model.predict(eval_data)
i = 0
# Plot the first X test images, their predicted labels, and the true labels.
# 预测15个数据
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
    plt.subplot(num_rows, 2*num_cols, 2*i+1)
    plot_image(i, predictions[i], eval_labels, eval_data)
    plt.subplot(num_rows, 2*num_cols, 2*i+2)
    plot_value_array(i, predictions[i], eval_labels)
plt.tight_layout()
plt.show()
predictions[0]
np.argmax(predictions[0])
eval_labels[0]

# Grab an image from the test dataset.
# img = eval_data[3]
# print(img.shape)
# # Add the image to a batch where it's the only member.
# img = (np.expand_dims(img,0))
# print(img.shape)
# predictions_single = model.predict(img)
# print(predictions_single)
# plot_value_array(1, predictions_single[0], eval_labels)
# _ = plt.xticks(range(10), class_names, rotation=45)

# np.argmax(predictions_single[0])


# 预测
# plt.figure(figsize=(10,10))
# for i in range(25):
#     plt.subplot(5,5,i+1)
#     plt.xticks([])
#     plt.yticks([])
#     plt.grid(False)
#     plt.imshow(train_data[i], cmap=plt.cm.binary)
#     plt.xlabel(class_names[train_labels[i]])
# plt.show()

# 查看原始第一个图像
# plt.figure()
# plt.imshow(train_data[0])
# plt.colorbar()
# plt.grid(False)
# plt.show()
